package com.report.word;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.Configure.AbortHandler;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.policy.RenderPolicy;
import com.report.TemplateContext;
import com.report.TemplateEngine;
import com.report.TemplateType;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

public class WordTemplateEngine implements TemplateEngine {

    @Override
    public void processTemplate(InputStream template, OutputStream output, TemplateContext context) throws IOException {

        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL();
        builder.setValidErrorHandler(new AbortHandler());

        Map<String, Object> root = context.getData();
        builder.setRenderDataComputeFactory(new CustomRenderFactory(root));

        CustomTextRenderPolicy policy = new CustomTextRenderPolicy();
        builder.addPlugin('\0', policy);

        Configure configure = builder.build();
        Map<Character, RenderPolicy> map = configure.getDefaultPolicys();
        map.remove('#');

        XWPFTemplate result = XWPFTemplate.compile(template, configure).render(root);
        result.write(output);
        result.close();
        output.flush();
        output.close();
    }

    @Override
    public TemplateType getTemplateType() {
        return TemplateType.WORD;
    }

}
